package cn.yd.rb.service.serviceimpl;

import cn.yd.rb.mapper.ChapterMapper;
import cn.yd.rb.po.*;
import cn.yd.rb.service.ChapterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
@Transactional
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Override
    public void addChapter(Chapter chapter) {
        chapterMapper.insertSelective(chapter);
    }

    @Override
    public PageBean<Chapter> findAllChapterForNovel(Integer isAdmin,HttpSession session,Integer pc, Integer pageSiez, ChapterQueryVo chapterQueryVo,Integer id) {

        PageBean<Chapter> pb = new PageBean<Chapter>();


        User user= (User) session.getAttribute("user");
        Integer userVip= (Integer) session.getAttribute("userVip");

        Novel novel= (Novel) session.getAttribute("novelSession");

        ChapterExample chapterExample = new ChapterExample();
        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        //添加条件
        criteria.andNovelIdEqualTo(id);
        if(isAdmin==1){
            PageHelper.startPage(pc, pageSiez);//计算分页数据
            chapterExample.setOrderByClause("id asc");
        }else{
            if(user==null){
                chapterExample.setOrderByClause("id asc limit 1");
            }else{
                if(userVip==1){
                    PageHelper.startPage(pc, pageSiez);//计算分页数据
                    chapterExample.setOrderByClause("id asc");
                }else{
                    if(novel.getIsFree()==0){
                        PageHelper.startPage(pc, pageSiez);//计算分页数据
                        chapterExample.setOrderByClause("id asc");
                    }else{
                        chapterExample.setOrderByClause("id asc limit 1");
                    }
                }

            }
        }
        //存放条件
        String searchStr = "";

        pb.setUrl(searchStr);

        List<Chapter> list = chapterMapper.selectByExample(chapterExample);

        pb.setBeanList(list);//将当前页显示的记录存入集合

        PageInfo<Chapter> info = new PageInfo<Chapter>(list);
        pb.setInfo(info);

    //    System.out.println(pb.getInfo().getTotal());

        return pb;
    }
}
